<template>
  <el-select v-model="currentValue" :disabled="disabled" filterable remote :placeholder="placeholder" :style="{'display': block?'block':'inline-block'}" :clearable="clearable" :remote-method="remoteMethod" @change="change">
    <el-option v-for="(item,index) in optionList" :key="index" :label="item.label + (item.value?`(${item.value})`:'')" :value="item.value"></el-option>
  </el-select>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: "ApeDictSelector",
  props: {
    block: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    code: {
      type: String,
      default: ''
    },
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  data() {
    return {
      currentValue: this.value,
      items: [],
      optionList: []
    };
  },
  computed: {
    ...mapGetters(['dicts'])
  },
  watch: {
    value(newValue) {
      this.currentValue = newValue;
    }
  },
  mounted() {
    this.load();
  },
  methods: {
    change(val) {
      this.$emit("input", val);
      this.$emit("change", val);
    },
    load() {
      var dict = this.dicts.find(n => n.code === this.code);
      this.items = dict && dict.items && dict.items.filter(n => n.is_active === true);
      this.optionList = this.items;
    },
    remoteMethod(query) {
      if (query) {
        this.optionList = this.items.filter(item => {
          return item.value.toLowerCase().indexOf(query.toLowerCase()) > -1 || item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this.optionList = this.items;
      }
    }
  }
};
</script>
